import { EmployeeLoginComponent } from './../employeeLogin/employeeLogin.component';
import { NavController } from 'ionic-angular';
import { MdSnackBar } from '@angular/material';
import { Terminal } from './../../model/clerkDataContext';
import { SystemService } from './../../service/system.service';
import { NavigateService } from './../../service/navigate.service';
import { Component, Input, OnInit, HostListener } from '@angular/core';
import { MessageBoxService, MessageResult, GrowlMessageType } from '../../component/messageBoxService';
import { loadingMask } from './../../component/decorators';

@Component({
    //moduleId: module.id,
    selector: 'bind-device',
    templateUrl: './bindDevice.component.html',
    styleUrls: ['./bindDevice.component.scss']
})

export class BindDeviceComponent implements OnInit {
    constructor(
        private router: NavigateService,
        private sysSvr: SystemService,
        private msgSvr: MessageBoxService,
        public snackBar: MdSnackBar,
        public navCtrl: NavController
    ) { }

    title: string = "店铺名称";
    store = <any>this.sysSvr.CurrentStore;
    terminal: Terminal = <any>{};
    deviceName = "";

    @HostListener('document:keyup', ['$event'])
    onKeyUp(ev: KeyboardEvent) {
        if (ev.keyCode == 13) {
            this.onStart();
        }
    }

    async ngOnInit() {
        let result = await this.sysSvr.getTerminalName();
        if (result) {
            this.deviceName = result.terminalName;
        }
    }

    @loadingMask()
    async onStart() {
        try {
            if (!this.deviceName) {
                this.msgSvr.Growl(GrowlMessageType.Warning, this.snackBar, "终端名称不能为空");
                return;
            }
            let result = await this.sysSvr.BindTerminal(this.deviceName);
            this.terminal.id = result.id;
            this.terminal.name = result.name ? result.name : "";
            this.sysSvr.Terminal = this.terminal;
            // this.router.navigate(["employeeLogin"]);
            this.navCtrl.setRoot(EmployeeLoginComponent);
        } catch (error) {
            this.msgSvr.Growl(GrowlMessageType.Error, this.snackBar, error ? error : "绑定终端出错");
        }
    }

    onBack() {
        this.router.navigate(["selectStore"]);
    }
}